<template>
	<div class="row">
		<div class="col-sm-12 col-md-8">
			<table class="table">
				<thead class="thead-defaule">
					<tr>
						<th>尺寸</th>
						<th>价格</th>
						<th>加入</th>
						
					</tr>
				</thead>
				<tbody v-for="item,index in getMenuItems">
					<tr>
						<td><strong>{{item.name}}</strong></td>
					</tr>
					<tr>
						<td>{{item.size}}</td>
						<td>{{item.price}}</td>
						<td><button @click="addToCart1(index)" class="btn btn-sm btn-outline-success">+</button></td>
					</tr>
				</tbody>
				
			</table>
		</div>
		<!-- 购物车 -->
		
			<div class="col-sm-12 col-md-4">
				<div v-if="cart.length>0">
					<table class="table">
						<thead class="thead-defaule">
							<tr>
								<th>数量</th>
								<th>价格</th>
								<th>品种</th>
							</tr>
						</thead>
						<tbody v-for="item,index in cart" :key="index">
							<td style="padding: 12px 0;">
								<button @click="less(item,index)" class="btn btn-sm btn-success">-</button>
								<span style="padding: 0 5px;">{{item.num}}</span>
								<button @click="more(item)" class="btn btn-sm btn-success">+</button>
							</td>
							<td>{{item.price*item.num}}</td>
							<td>{{item.name}}</td>
						</tbody>
					</table>
					<p>总价:{{sumPrice}}</p>
					<button class="btn btn-success btn-block">
						提交	
					</button>
				</div>
				<div v-else>
					购物车没有任何商品
				</div>
			</div>
		
	</div>
</template>

<script>
	import axios from 'axios'
	export default{
	  data(){
			return{
				cart:[],
				
			
			}
		},
		created() {
			fetch('/mock/admain/admain.json').then(data=>{
				return data.json()
			}).then(res=>{
				this.$store.commit('setMenuItems',res.data)
				// this.getMenuItems=res.data
		
			})
		},
	computed:{
		sumPrice(){
		return this.cart.reduce((total,cart)=>{
				return total+ cart.price*cart.num
			},0)
		},
		getMenuItems(){
			
			return this.$store.state.menu.menuItems
		}
	},
		methods:{
			
			addToCart1(index){
	
				let i=0;
				for (let s of this.cart) {
					if(s.name===this.getMenuItems[index].name){
						s.num++;
						i++;
						break;
					}
				}
					if(i==0){
						this.cart.push({
							name:this.getMenuItems[index].name,
							price:this.getMenuItems[index].price,
							size:this.getMenuItems[index].size,
							num:1
							})
					}
					console.log(this.getMenuItems[index].name)
			},
			
			more(item){
				console.log(item)
				item.num++
			},
			less(item,index){
				item.num--
				if(item.num!==0){
					return;
				}else{
				
					this.cart.splice(index,1)
				}
			},
			
		}
	}
</script>

<style>
	button{
		outline: none;
	}
</style>
